
$(function(){
    var option = {
        theme:'vsStyle',
        expandLevel : 1,
        beforeExpand : function($treeTable, id) {
            //判断id是否已经有了孩子节点，如果有了就不再加载，这样就可以起到findMachineAndClientquota缓存的作用
            if ($('.' + id, $treeTable).length) { return; }
            var userName = $("#"+id).attr("userNameFlag");
            $.ajax({
                url: "findMachineAndClientquota.do",
                data: {"userId":id},
                dataType: "json",
                async:false,
                success: function (data) {
                    var html="";
                    if(data!=null && data.length>0){
                        for (var j = 0; j < data.length; j++) {
                            var s=data[j];
                            html +="<tr id="+id+s.id+" pId="+id+" flag='rowspan'>"
                            +"<input type='hidden' id='userId' value='"+ id+"'/>"
                            +"<input type='hidden' id='clientquotaId' value='"+ s.clientquotaId+"'/>"
                            +"<input type='hidden' id='machineIdHidden' value='"+ s.id+"'/>"
                            +"<input type='hidden' id='clientCatalogHidden' value='"+ s.clientCatalog+"'/>"
                            +"<input type='hidden' id='machineIp' value='"+ s.machineIp+"'/>"
                            if(s.check=="true"){
                                html +="<td><input type='checkbox' value='"+ s.id+"' name='machineId' id='machineId' checked='checked' onclick=\"kerberidCheck(this,'"+ (id+ s.id)+"','"+ s.clientquotaId+"')\"></td>"
                            }else{
                                html +="<td><input type='checkbox'value='"+ s.id+"' name='machineId' id='machineId' onclick=\"kerberidCheck(this,'"+ (id+ s.id)+"','"+ s.clientquotaId+"')\"></td>"
                            }
                            html +="<td>"+ s.machineIp+"</td>"
                            html +="<td>"+ s.note+"</td>"
                            html +="<td>"+ s.clusterTypeName+"</td>"
                            html +="<td id='catalog_td'><select name='clientCatalog' id='clientCatalog' value='"+ s.clientCatalog+"' disabled style='width:90%'>"
                            html +="</select></td>"
                            html +="<td><input name='clientCatalogSize' id='clientCatalogSize' value='"+ (s.clientCatalogSize==null?'':s.clientCatalogSize)+"' onkeyup=\"this.value=this.value.replace(/\\D/g,'')\" style='width:90%'></td>"
                            html +="<td><select name='clientCatalogUnit' id='clientCatalogUnit' value='"+ s.clientCatalogUnit+"' style='width:60%'>"
                            if(s.clientCatalogUnit == "T"){
                                html +="<option value='T' selected>T</option>"
                                html +="<option value='G'>G</option>"
                                html +="<option value='M'>M</option>"
                            }else if(s.clientCatalogUnit == "G"){
                                html +="<option value='T'>T</option>"
                                html +="<option value='G' selected>G</option>"
                                html +="<option value='M'>M</option>"
                            }else if(s.clientCatalogUnit == "M"){
                                html +="<option value='T'>T</option>"
                                html +="<option value='G'>G</option>"
                                html +="<option value='M' selected>M</option>"
                            }else{
                                html +="<option value='T'>T</option>"
                                html +="<option value='G'>G</option>"
                                html +="<option value='M'>M</option>"
                            }
                            html +="</select></td>"
                            html +="</tr>"
                        }
                    }
                    $treeTable.addChilds(html);
                    findClientquota(userName);
                    clientCatalogFlag();
                }
            })

        },
        onSelect : function($treeTable, id) {
            window.console && console.log('onSelect:' + id);
        }
    };
    //加载treeTable
    $('#treeTable1').treeTable(option);
});

function findClientquota(hp_username){
    //修改界面，给用户目录设置默认值update20160824
    $.ajax({
        url: "findClientHome.do",
        data: "userName=" + hp_username ,
        type: "post",
        dataType: "json",
        async:false,
        success: function (data) {
            if(data != null && data != ""){
                $("td[id*='catalog_td']").each(function(){
                    var tdThis = $(this);
                    tdThis.find("select[id='clientCatalog']").each(function(){
                        if(tdThis.parent().find("input[id='machineId']").attr("checked") && tdThis.parent().find("input[id='clientquotaId']") !=null && tdThis.parent().find("input[id='clientquotaId']") !=""){
                            $(this).append("<option value='"+tdThis.parent().find("input[id='clientCatalogHidden']").val()+"'>"+tdThis.parent().find("input[id='clientCatalogHidden']").val()+"</option>");
                        }else{
                            $(this).empty();
                            for( i=0;i<data.length;i++){
                                $(this).append("<option value='"+data[i]+"'>"+data[i]+"</option>");
                            }
                        }
                    });
                });
            }
        },
        error: function () {
        }
    })
}

//勾选checkbox的事件
function kerberidCheck(obj,trId,clientquotaId) {
    if (obj.checked) {
        obj.setAttribute("checked","checked");
        if(clientquotaId != null && clientquotaId !="" && clientquotaId != "undefined" ){
            $("#"+trId).find("select[id='clientCatalog']").attr("disabled",true);
        }else{
            $("#"+trId).find("select[id='clientCatalog']").removeAttr("disabled");
        }
        $("#"+trId).find("input[id='clientCatalogSize']").removeAttr("disabled");
        $("#"+trId).find("select[id='clientCatalogUnit']").removeAttr("disabled");
    }else{
        obj.removeAttribute("checked");
        $("#"+trId).find("select[id='clientCatalog']").attr("disabled",true);
        $("#"+trId).find("input[id='clientCatalogSize']").attr("disabled",true);
        $("#"+trId).find("select[id='clientCatalogUnit']").attr("disabled",true);
    }
}

//用户目录是否可编辑
function clientCatalogFlag() {
    $("tr").each(function(){
        if($(this).find("input[id='machineId']").attr("checked")){
            if(clientquotaId != null && clientquotaId !="" && clientquotaId != "undefined"  ) {
                $(this).find("select[id='clientCatalog']").attr("disabled",true);
            }else{
                $(this).find("select[id='clientCatalog']").removeAttr("disabled");
            }
            $(this).find("input[id='clientCatalogSize']").removeAttr("disabled");
            $(this).find("select[id='clientCatalogUnit']").removeAttr("disabled");
        }else{
            $(this).find("select[id='clientCatalog']").attr("disabled",true);
            $(this).find("input[id='clientCatalogSize']").attr("disabled",true);
            $(this).find("select[id='clientCatalogUnit']").attr("disabled",true);
        }
    });

}

function saveBatch(){
    var clientList = "";
    var kerList = "";
    var hdfsList = "";
    var noSelectList = "";
    var kerFlag = true;
    $("tr[parentTr]").each(function () {
        var userId = $(this).attr("id");
        var hdfsId = $(this).find("input[id='hdfsquotaid']").val();
        var hdfsSpace = $(this).find("input[id='hdfsSpace']").val();
        var hdfsSpaceUnit = $(this).find("select[id='hdfsSpaceUnit']").val();
        var hdfsFileCount = $(this).find("input[id='hdfsFileCount']").val();
        var validDay = $(this).find("input[id='validDay']").val();
        var machineIds = [];
        var noSelectMachineIds = [];
        $("tr[pId="+userId+"]").each(function (){
            if($(this).find("input[id='machineId']").attr("checked") == "checked"){
                machineIds.push($(this).find("input[id='machineId'][checked='checked']").val());
            }
            var clientquotaId = $(this).find("input[id='clientquotaId']").val();
            if($(this).find("input[id='machineId']").attr("checked") == undefined && (clientquotaId !=null ||clientquotaId!="")){
                noSelectMachineIds.push($(this).find("input[id='machineId']").val());
            }
        });
        noSelectList += '{"userId":' + userId + ',"noSelectMachineIds":"' + noSelectMachineIds.toString() + '"}'+";";
        var ker = "";
        if(validDay!=null && validDay != ""){
            var valid = parseInt(validDay);
            var now = new Date();
            var fDate = formatDate(now);
            var start = fDate;
            var end = "";
            var loseTime = "";
            if (valid == 0) {
                end='永久';
                loseTime='永久';
            } else if (valid > 0) {
                now.setDate(now.getDate() + valid);
                var fDate = formatDate(now);
                end = fDate;
                loseTime=valid;
            } else {
                end= "";
                loseTime="";
            }
            ker ='{"userId":' + userId + ',"validDay":"' + validDay + '","machineIds":"' + machineIds.toString()+ '","startTime":"' + start+ '","endTime":"' + end+ '","status":"0"}';
            kerList += ker + ";";
        }else{
            alert("请填写有效期！");
            kerFlag = false;
            return;
        }
        if (hdfsSpace == "") {
            hdfsSpace = 0;
        }
        if (hdfsFileCount == "") {
            hdfsFileCount = 0;
        }
        var hdfs = "";
        if(hdfsId != null && hdfsId !="" && hdfsId != "undefined" && hdfsId != undefined){
            hdfs = '{"id":'+hdfsId+',"userId":'+userId+',"hdfsSpace":"' + hdfsSpace + '","hdfsSpaceUnit":"' + hdfsSpaceUnit + '","hdfsFileCount":"' + hdfsFileCount + '"}';
        }else{
            hdfs = '{"userId":'+userId+',"hdfsSpace":"' + hdfsSpace + '","hdfsSpaceUnit":"' + hdfsSpaceUnit + '","hdfsFileCount":"' + hdfsFileCount + '"}';
        }

        hdfsList  += hdfs+";";
    });
    if(!kerFlag){
        return;
    }
    var index = 0 ;

    $("tr[pId]").each(function () {
        if($(this).find("input[id='machineId']").attr("checked") == "checked"){
            var userId = $(this).find("input[id='userId']").val();
            var clientquotaId = $(this).find("input[id='clientquotaId']").val();
            var machineIdHidden = $(this).find("input[id='machineIdHidden']").val();
            var clientCatalog = $(this).find("select[id='clientCatalog']").val();
            var clientCatalogSize = $(this).find("input[id='clientCatalogSize']").val();
            var clientCatalogUnit = $(this).find("select[id='clientCatalogUnit']").val();
            if(clientCatalog == null || clientCatalog==""){
                alert("请填写用户目录！");
                return false;
            }
            if(clientCatalogSize == null || clientCatalogSize==""){
                clientCatalogSize = 0;
            }
            var client = "";
            if(clientquotaId == null || clientquotaId == "" || clientquotaId == "undefined"){
                client ='{"clientCatalog":"' + clientCatalog + '","clientCatalogSize":"' + clientCatalogSize + '", "clientCatalogUnit":"' + clientCatalogUnit + '", "userId":"' + userId + '", "machineId":"' + machineIdHidden + '"}';
            }else{
                client ='{"id":' + clientquotaId + ',"clientCatalog":"' + clientCatalog + '","clientCatalogSize":' + clientCatalogSize + ', "clientCatalogUnit":"' + clientCatalogUnit + '", "userId":' + userId + ', "machineId":"' + machineIdHidden + '"}';
            }
            clientList += client + ";";
        }
        index ++;
    })
    //console.log("noSelectList.toString()==="+noSelectList.toString());
    //console.log("kerList.toString()==="+kerList.toString());
    //console.log("hdfsList.toString()==="+hdfsList.toString());
    //console.log("clientList.toString()==="+clientList.toString());
    $.ajax({
        type: 'post',
        url: "saveBatchUpdate.do",
        data: {
            "hdfsList": hdfsList.toString(),
            "clientList": clientList.toString(),
            "kerList": kerList.toString(),
            "noSelectList":noSelectList.toString()
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        success: function (data) {
            var message = data.data.message;
            if (data.success) {
                var message = data.data.message;
                console.log(message);
                if (data.data.type == 'error') {
                    var message = data.data.message;
                    layer.open({
                        title: '提示信息',
                        content: message,
                        maxWidth: 630
                    });
                } else {
                    var message = message.replace(/, /g, '<br/>');
                    parent.layer.config({
                        extend: ['skin/moon/style.css'] //加载新皮肤
                    });
                    parent.layer.open({
                        title: '提示信息',
                        area: ['630px', '300px'],
                        content: message,
                        extend: ['skin/moon/style.css'],
                        skin: 'layer-ext-moon',
                        yes: function (index) {
                            parent.window.location.reload();
                            parent.layer.close();
                        },
                        cancel: function(index){
                            parent.window.location.reload();
                            parent.layer.close();
                        }
                    });
                }
            } else {
            }
        }
    })
}

function kerbersValidDay_update(obj) {
    obj.value = obj.value.replace(/\D/g, '')
    var valid = parseInt(obj.value);
    var now = new Date();
    var fDate = formatDate(now);
    $("#start").val(fDate);
    if (valid == 0) {
        $("#end").val('永久');
        $("#loseTime").val('永久');
    } else if (valid > 0) {
        now.setDate(now.getDate() + valid);
        var fDate = formatDate(now);
        $("#end").val(fDate);
        $("#loseTime").val(valid);
    } else {
        $("#end").val('');
        $("#loseTime").val('');
    }
}

function formatDate(now) {
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ss = now.getSeconds();            //秒
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm+":";
    if (ss < 10) clock += '0';
    clock += mm;
    return clock;
}

function checkHdfsSpace(obj) {
    var value = $(obj).val();
    if (!/^[0-9]*\.?[0-9]+$/.test(value)) {
        $("#hdfsSpace").val("");
    }
}
/*

function closeWin() {
    parent.thirdWin.close();
}*/
